package ua.com.minus1.lookbattle;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.widget.*;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import ua.com.minus1.lookbattle.models.CommonResult;
import ua.com.minus1.lookbattle.models.Country;
import ua.com.minus1.lookbattle.net.HttpFileCache;
import ua.com.minus1.lookbattle.net.HttpManager;
import ua.com.minus1.lookbattle.net.MultipartUploader;
import ua.com.minus1.lookbattle.utils.AppPreferences;
import ua.com.minus1.lookbattle.utils.BundleCreator;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Flash
 * Date: 13.07.12
 * Time: 16:11
 * To change this template use File | Settings | File Templates.
 */
public class TakePictureActivity extends FragmentActivity {

    private static final int CHOOSE_COUNTRY_DIALOG = 0;
    private static final int TAKE_PICTURE = 0;
    private static final int SELECT_PICTURE = 1;
    private ImageView tempImage;
    private File imageFile;

    private static final String TAG = "TakePictureActivity";
    private AppPreferences preferences;
    private String uuid;
    private HttpFileCache fileCache;
    private int catId;
    private ViewFlipper viewFlipper;
    private Spinner countrySpinner;
    private List<Country> countries;
    private Button countryBtn;
    private ArrayAdapter<Country> countriesAdapter;
    private Country currentCountry;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.take_picture);

        catId = BundleCreator.readCategory(getIntent().getExtras());

        fileCache = new HttpFileCache(this, "looks");

        preferences = new AppPreferences(this);
        uuid = preferences.getUUID();
        currentCountry = preferences.getCountry();

        setupViews();
    }

    private void setupViews() {
        viewFlipper = (ViewFlipper) findViewById(R.id.takePictureViewFlipper);
        tempImage = (ImageView) findViewById(R.id.tempImage);
        countryBtn = (Button) findViewById(R.id.takePictureCountryButton);
        countryBtn.setOnClickListener(new CountryClickListener());
        if(currentCountry != null)
            countryBtn.setText(currentCountry.name);
        //countrySpinner = (Spinner) findViewById(R.id.takePictureCountrySpinner);

        countries = CountriesFactory.getCountries(this);
        countriesAdapter = new ArrayAdapter<Country>(this, android.R.layout.simple_spinner_dropdown_item, countries);
        //countriesAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
        //countrySpinner.setAdapter(countriesAdapter);
    }


    public void takePicture(View view) {
        imageFile = getEmptyFile("look.jpg");
        if(imageFile != null){
            Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(imageFile));
            startActivityForResult(i, TAKE_PICTURE);
        }
    }

    public void pickPicture(View view) {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case TAKE_PICTURE:
                    BitmapFactory.Options opts = new BitmapFactory.Options();
                    opts.inJustDecodeBounds = true;
                    BitmapFactory.decodeFile(imageFile.getPath(), opts);
                    Log.i(TAG, opts.outWidth + "x" + opts.outHeight);
                    break;
                case SELECT_PICTURE:
                    Uri selectedImageUri = data.getData();

                    String fileManagerPath = selectedImageUri.getPath();
                    String galleryPath = getPath(selectedImageUri);

                    if(galleryPath != null)
                        imageFile = new File(galleryPath);
                    else
                        imageFile = new File(fileManagerPath);
            }
            updatePicture(imageFile.getPath());
            viewFlipper.showNext();
        }
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case CHOOSE_COUNTRY_DIALOG:
                AlertDialog.Builder builder = new AlertDialog.Builder(this)
                        .setTitle("Please choose country")
                        .setAdapter(countriesAdapter, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialogInterface, int i) {
                                currentCountry = countries.get(i);
                                countryBtn.setText(currentCountry.name);
                                preferences.setCountry(currentCountry);
                            }
                        });
                return builder.create();
        }
        return null;
    }

    private void updatePicture(String path) {
        tempImage.setImageBitmap(BitmapFactory.decodeFile(path));
    }

    private String getPath(Uri uri) {
        String[] projection = {MediaStore.Images.Media.DATA};
        Cursor cursor = managedQuery(uri, projection, null, null, null);

        if (cursor != null) {
            int columnIndex = cursor.getColumnIndex(projection[0]);
            if(columnIndex == -1)
                return null;
            cursor.moveToFirst();
            return cursor.getString(columnIndex);
        }
        return null;
    }

    public void cancelTakePicture(View view) {
        setResult(RESULT_CANCELED);
        finish();
    }

    public void cancelLook(View view) {
        viewFlipper.showPrevious();
    }

    public void uploadLook(View view) {
        MultipartUploader uploader = new MultipartUploader();
        int countryId = currentCountry != null ? currentCountry.id : -1;
        uploader.uploadLook(this, uuid, catId, countryId, imageFile, new HttpManager.HttpResultHandler<CommonResult>() {
            public void onResultLoadComplete(CommonResult result) {
                setResult(RESULT_OK);
                finish();
            }
        });
    }

    private File getEmptyFile(String fileName) {
        File file = fileCache.getFile(fileName);
        try {
            if (file.exists()) {
                file.delete();
                file.createNewFile();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

    private class CountryClickListener implements View.OnClickListener {
        public void onClick(View view) {
            showDialog(CHOOSE_COUNTRY_DIALOG);
        }
    }
}
